#!/usr/bin/env groovy

pipeline {
    agent { label 'linter' }
    parameters{
        string(name: 'GITHUB_ORG', defaultValue: 'nodejs', description: 'The user/org of the GitHub repo')
        string(name: 'REPO_NAME', defaultValue: 'node', description: 'The name of the repo')
        string(name: 'GIT_REMOTE_REF', defaultValue: 'refs/heads/master', description: 'The remote portion of the Git refspec to fetch and test')
    }

    stages {
        stage("Setup repository") {
            steps {
                checkout(changelog: false, poll: false, scm: [
                    $class: 'GitSCM',
                    branches: [[
                        name: 'refs/heads/_jenkins_local_branch'
                    ]],
                    userRemoteConfigs: [[
                        credentialsId: "96d5f81c-e9ad-45f7-ba5d-bc8107c0ae2c",
                        url: "git@github.com:${params.GITHUB_ORG}/${params.REPO_NAME}",
                    ]]
                ])
            }
        }

        stage('Pre-flight') {
            steps {
                sh "curl -L -s https://raw.githubusercontent.com/nodejs/build/master/jenkins/scripts/node-test-commit-pre.sh -s | bash -xe"
                sendBuildStatus("pending", env)
                checkMake()
                // Make sure we have a node binary in the path 
                sh 'node --version'
            }
        }


        stage('Build linting tools') {
            steps {
                // Calling with `returnStatus` suppresses automatic failures
                sh(script: "${env.MAKE} lint-md-build", returnStatus: true)
                sh(script: "${env.MAKE} lint-py-build", returnStatus: true)
            }
        }
         
        stage('Run tests') {
            steps {
                script {
                    def node_version = sh(script: "python  tools/getnodeversion.py", returnStdout: true).trim()
                    echo node_version
                    def node_version_parts = node_version.tokenize('.')
                    def node_major = node_version_parts[0] as int
                    def lint_py3_ret = 0
                    if (node_major > 11) {
                    // this job does not build node, so we use the system's node 
                      lint_py3_ret = sh(script: "NODE=node PYTHON=python3 ${env.MAKE} lint-py", returnStatus: true)
                    }
                    // this job does not build node, so we use the system's node 
                    def ret = sh(script: "NODE=node ${env.MAKE} lint-ci", returnStatus: true)
                    if (ret != 0 || lint_py3_ret != 0) {
                        echo(extractErrors())
                        error('lint failed - open above section for details')
                    }
                }
            }
        }
    }

    post {
        success {
            sendBuildStatus("success", env)
        }

        failure {
            sendBuildStatus("failure", env)
        }
    }
}

def extractErrors() {
    def tap = readFile('test-eslint.tap')
    tap = tap.replaceAll('(?m)^ok.*', '')
    tap = tap.replaceAll('(?m)^TAP version 13.*', '')
    tap = tap.replaceAll('(?m)^1\\.\\..*', '')
    tap = tap.replaceAll('(?m)^\\s+$', '')
    return tap
}

def tap2JUnit() {
    fileOperations([folderCreateOperation('out/junit')])
    def status = sh(returnStatus: true, script: 'tap2junit -i test-eslint.tap -o out/junit/test-eslint.xml')
    if (status == 0) {
        junit(allowEmptyResults: true, testResults: 'out/junit/*.xml')
    }
}

def checkMake() {
    def status = sh(returnStatus: true, script: "which gmake")
    if (status != 0) {
        env.MAKE = 'make'
    } else {
        env.MAKE = 'gmake'
    }
}


def sendBuildStatus(status, env) {
    build job: 'post-build-status-update', parameters: [
              string(name: 'REPO', value: 'node'),
              string(name: 'IDENTIFIER', value: 'linter'),
              string(name: 'URL', value: env.BUILD_URL),
              string(name: 'COMMIT', value: sh(script: 'git rev-parse HEAD', returnStdout: true).trim()),
              string(name: 'REF', value: env.GIT_REMOTE_REF),
              string(name: 'STATUS', value: status)
          ]
}
